from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from extensions import db

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(256))
    is_active = db.Column(db.Boolean, default=True)
    role = db.Column(db.String(20), default='user')  # user, admin
    
    # 用户信息
    name = db.Column(db.String(64))
    avatar = db.Column(db.String(128))
    bio = db.Column(db.Text)
    
    # 时间戳
    created_at = db.Column(db.DateTime, server_default=db.func.now())
    updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
    
    # 用于存储用户点赞的帖子ID
    _liked_posts = db.Column('liked_posts', db.Text, default='')
    
    @property
    def liked_posts(self):
        if not self._liked_posts:
            return set()
        return {int(x) for x in self._liked_posts.split(',') if x}
    
    @liked_posts.setter
    def liked_posts(self, value):
        if isinstance(value, set):
            self._liked_posts = ','.join(str(x) for x in value)
        else:
            self._liked_posts = str(value)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f'<User {self.username}>' 